// stores/user.ts
import { defineStore } from "pinia";
import { fetchMenuListApi } from "@/api/modules/menu";
import type { MenuItem } from "@/types/menu";

export const useMenuStore = defineStore("menu", {
  state: () => ({
    menuTree: [] as MenuItem[],
  }),
  getters: {},
  actions: {
    async fetchMenuTree() {
      try {
        const res = await fetchMenuListApi();
        const data = res.data?.data || res.data; // 更安全的访问方式
        if (data) {
          this.menuTree = data;
          return data;
        }
        throw new Error("菜单数据格式错误");
      } catch (error) {
        console.error("获取菜单失败:", error);
        throw error;
      }
    },
  },
  persist: {
    enabled: true,
    strategies: [
      {
        key: "menu",
        storage: localStorage,
      },
    ],
  },
});
